package seig.wjy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import seig.wjy.domain.pojo.GraduationTopic;
import seig.wjy.domain.pojo.User;
import seig.wjy.domain.vo.LoginUser;
import seig.wjy.mapper.UserMapper;
import seig.wjy.service.LoginService;
import seig.wjy.tools.JwtUtil;

import java.util.Objects;

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper,User> implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectUser(String username){
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public String login(User user) {
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(authentication);
            if(Objects.isNull(authenticate)){
                throw new RuntimeException("登陆失败");
            }
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            String loginUserString = JSON.toJSONString(loginUser);
            String jwt = JwtUtil.createJWT(loginUserString);
//            try {
//                stringRedisTemplate.opsForValue().set("login:"+loginUser.getUser().getId(), loginUserString);
//            }catch (Exception e){
//                e.printStackTrace();
//            }
            return jwt;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}
